<?php

/**
 * 重庆谖草 SDK
 * @author chenyun
 */

namespace App\Service\VendorClient\Shopcqxc;
use App\Model\PssModel\ServiceConfig;
use App\Service\Code\Normal;
use App\Service\AppService\SystemCacheConfigService;
use App\Service\TaskServer\TaskWorker;
use Service\AppService\IdService;

class ShopcqxcApiClient
{
    private $account  = 'shopcqxc';
    protected $config;
    /**
     * 初始参数
     * @param obj $collection
     */
    public function __construct( $apiBody = [] ) 
    {
        $this->config = $apiBody;
    }
    
    /**
     * 创建订单
     */
    public function createOrder( $params = [] ) 
    {   
        ini_set('serialize_precision', '14');
        
        if( empty($params['supplierOrder']) || empty($params['orderGoods']) || empty($params['order']) || empty($params['binfo']) ) {
            return Normal::returnCode(Normal::FAIL,"except param supplierOrder or orderGoods or order or binfo");
        }
        //组装订单参数
        $orderInfo = $params['supplierOrder'];
        $order     = $params['order'];
        $binfo     = $params['binfo'];
        //运费
        $deliver_money  = $orderInfo['deliver_money'];
        //商品下单组
        $orderGoodsList = [];
        $productAmt     = $TaxAmt = 0 ;
        foreach ($params['orderGoods'] as $key => $item )
        {
            //卖价
            $price              = $item['price'];
            //商品购买规格数量
            $spec_num           = $item['spec_num'];
            //商品购买数量(下单数量 X 起售数量)
            $quantity           = $item['quantity'];
            //实际购买数量
            $buyAcount          = $spec_num * $quantity ;
        
            //商品单价包含税金
            if( $key == 0 ) {
                $singleDeliveryMoney = bcdiv((string)$deliver_money,(string)$quantity,3);
                $singleDeliveryMoney = bcmul((string)$singleDeliveryMoney,(string)100,1);
                $singleDeliveryMoney = bcdiv((string)ceil($singleDeliveryMoney), (string)100,2);
                $price               = bcadd((string)$price, (string)$singleDeliveryMoney,2);
            }
        
            //单个商品价格
            $singleGoodsPrice   = bcdiv((string)$price, (string)$spec_num,3);
            $singleGoodsPrice   = ceil(bcmul((string)$singleGoodsPrice,(string)'100',1));
            $singleGoodsPrice   = bcdiv((string)$singleGoodsPrice,'100',2);
            $totalGoods         = bcmul((string)$singleGoodsPrice,(string)$buyAcount,2);
            //商品组
            $orderGoodsList[] = [
                'goodsCode' => $item['supplier_skucode'],
                'qty'       => $buyAcount,
                'price'     => (float)$singleGoodsPrice,
                'remark'    => $item['goods_name'],
            ];
            $productAmt = bcadd((string)$productAmt,(string)$totalGoods,2);
        }
        
        $deduction  =0;
        //实际下单金额
        $real_total_money = $orderInfo['real_total_money'];
        
        //优惠金额
        $discount_money = bcsub((float)$productAmt,(float)$real_total_money,2);
        
        //下单支付的时候支付信息
        $apply_extends  = @json_decode($orderInfo['apply_extends'],true);
        //支付时间
        $payTime        = empty($order['payTime']) ? $orderInfo['pay_time'] :$order['payTime'];
        //支付时间
        $pay_time       = $payTime ? $payTime : time();
        $pay_time       = date('Y-m-d H:i:s',$pay_time);
        
        //支付流水号
        $pay_sn         = $order['paySerial']??$orderInfo['pay_sn'];
        
        //获取系统配置地址
        $notifyInfo = SystemCacheConfigService::instance()->getCacheInfoBySystemCode('sysconfig');
        if( empty($notifyInfo['NotifyUrl']) ) {
            return Normal::returnCode(Normal::FAIL,"系统回调地址域名NotifyUrl不能为空");
        }
        
        //获取上游供应商支付方式路由
        $payCommanyCode = $apply_extends['payCommanyCode'] ?? '';
        $PayCompanyCode = $order['payCommanyCode'] ? $order['payCommanyCode'] : $payCommanyCode;
        $pay_value      = ServiceConfig::instance()->getConfigByEventsValue($this->account, ServiceConfig::TYPE_PAY, $PayCompanyCode);
        if (empty($pay_value)) {
            return Normal::returnCode(Normal::FAIL, "支付公司编码：【{$PayCompanyCode}】未映射，请联系管理员处理");
        } 
        
        //电商平台信息
        $enterpriseNum = $apply_extends['enterpriseNum'] ?? '';
        $enterpriseName = $apply_extends['enterpriseName'] ?? '';
        $enterpriseNum = $order['enterpriseNum'] ? $order['enterpriseNum'] : $enterpriseNum;
        $enterpriseName = $order['enterpriseName'] ? $order['enterpriseName'] : $enterpriseName;
        
        //创建订单数据
        $data = [
            'appkey'                => $this->config["appKey"],
            'method'                => 'order.add',
            'buyerRemark'           => $orderInfo['order_remark'],
            'customsPlatformCode'   => $enterpriseNum,
            'customsPlatformName'   => $enterpriseName,
            'declareOrderCode'      => $orderInfo['supplier_dsn'],
            'deduction'             => (float)$discount_money,
            'details'               => $orderGoodsList,
            'discount'              => 0,
            'expressCode'           => "",
            'freight'               => (float)'0.00',
            'orderTime'             => date("Y-m-d H:i:s",$orderInfo['cd']),
            'payments'              => [
                [
                    "amount"        => (float)$real_total_money,
                    "payTime"       => $pay_time,
                    "paymentCode"   => $pay_value,
                    "channelId"     => "",
                    "tradeNo"       => $pay_sn
                ]
            ],
            'platformOrderCode'   => $orderInfo['supplier_dsn'],
            'purchaser'           => $orderInfo['buyer_realname'],
            'purchaserCardNo'     => $orderInfo['buyer_idcard'],
            'purchaserCardType'   => 1,
            'purchaserTel'        => $orderInfo['buyer_phone'],
            'receiver'            => $orderInfo['receive_name'],
            'receiverAddress'     => $orderInfo['receive_address'],
            'receiverArea'        => $orderInfo['district'],
            'receiverCity'        => $orderInfo['city'],
            'receiverProvince'    => $orderInfo['province'],
            'receiverTel'         => $orderInfo['recveive_phone'],
            'shopCode'            => isset($this->config['shopCode']) ? $this->config['shopCode'] : "",
            'tax'                 => (float)$TaxAmt,
            'warehouseCode'       => "",
            'distributorsCode'    => isset($this->config['distributorsCode']) ? $this->config['distributorsCode'] : "",
            'shipperCode'         => "",
            'type'                => $this->config["type"],
            'notifyUrl'           => "{$notifyInfo['NotifyUrl']}/Notify/index/userType/{$this->account}/messageType/OrderAsyncNotify",
            'providerCode'        => "",
            'presell'             => $this->config["presell"],
            'planDeliveryTime'    => "",
        ];
        $requestParam = [
            'method'    => 'createOrder',
            'data'      => $data
        ];
        return $this->execute($requestParam);
    }
   
 
    /**
     * 取消订单
     */
    public function cancelOrder( $params = [] ) 
    {
        $data = [
            'appkey'                => $this->config["appKey"],
            'method'                => 'order.cancel.v2',
            'orderCode'             => $params['supplierOrder']['thirdpart_order_sn'],
            //'shopCode'              => $this->config["shopCode"],
        ];
        $requestParam = [
            'method'    => 'cancelOrder',
            'data'      => $data
        ];
        return $this->execute($requestParam);
    }
    /**
     * 加签
     * @param array $param
     */
    protected function getSign( array $param = [] )
    {
        $jsonBody = json_encode($param);
        $string = $this->config["appSecret"].$jsonBody.$this->config["appSecret"];
        return md5($string);
    }
    
    /**
     * CURL请求
     * @param $params
     * @return mixed
     */
    public function execute( $param = [] )  
    {
        if( empty($param['data']) ) {
            return Normal::returnCode(Normal::FAIL,"数据不能为空");
        }
        
        $method = $param['method'];
        $param['data']['sign'] = $this->getSign($param['data']);
        $url = $this->config['baseurl'];
        $parameter = [
            [
                'tag'       => $this->account.'_'.$method,
                'uid'       => IdService::instance()->getOtherID(),
                'url'       => $url,
                'data'      => $param['data'],
                'method'    => 'post',
                'format'    => 'json',
                'header'    => ["Content-Type: application/json"],
        
            ],
        ];
        
        $resTask = TaskWorker::instance()->addTask($parameter);
        $resTask = current($resTask);
        $res     = $resTask['response']['result'];
        $resHttp = json_decode($res,true);
        if( isset($resHttp['success']) && $resHttp['success'] == true ) {
            return Normal::returnCode(Normal::SUC,"操作成功",$resHttp);
        }
        $message = isset($resHttp['errorMsg']) ? $resHttp['errorMsg'] : '请求失败';
        return Normal::returnCode(Normal::FAIL,$message);
    }
}